<?php
/**
 * 健康检查脚本
 * 用于检查后端服务各项功能是否正常
 */

header('Content-Type: application/json; charset=utf-8');

$healthCheck = [
    'status' => 'healthy',
    'timestamp' => date('Y-m-d H:i:s'),
    'checks' => []
];

// 检查PHP版本
$phpVersion = phpversion();
$healthCheck['checks']['php_version'] = [
    'status' => version_compare($phpVersion, '7.4.0', '>=') ? 'healthy' : 'unhealthy',
    'version' => $phpVersion,
    'required' => '>=7.4.0'
];

// 检查必要的PHP扩展
$requiredExtensions = ['pdo', 'pdo_mysql', 'json', 'mbstring'];
foreach ($requiredExtensions as $ext) {
    $healthCheck['checks']['extension_' . $ext] = [
        'status' => extension_loaded($ext) ? 'healthy' : 'unhealthy',
        'loaded' => extension_loaded($ext)
    ];
}

// 检查配置文件
$configFiles = ['config/config.php', 'config/database.php'];
foreach ($configFiles as $file) {
    $healthCheck['checks']['config_' . basename($file)] = [
        'status' => file_exists(__DIR__ . '/' . $file) ? 'healthy' : 'unhealthy',
        'exists' => file_exists(__DIR__ . '/' . $file)
    ];
}

// 检查数据库连接
try {
    require_once __DIR__ . '/config/database.php';
    
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['database']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
    
    $healthCheck['checks']['database_connection'] = [
        'status' => 'healthy',
        'message' => '数据库连接成功'
    ];
    
    // 检查必要的表是否存在
    $requiredTables = ['users', 'foods', 'recipes', 'categories'];
    foreach ($requiredTables as $table) {
        $stmt = $pdo->query("SHOW TABLES LIKE '$table'");
        $exists = $stmt->rowCount() > 0;
        
        $healthCheck['checks']['table_' . $table] = [
            'status' => $exists ? 'healthy' : 'unhealthy',
            'exists' => $exists
        ];
    }
    
} catch (Exception $e) {
    $healthCheck['checks']['database_connection'] = [
        'status' => 'unhealthy',
        'error' => $e->getMessage()
    ];
    $healthCheck['status'] = 'unhealthy';
}

// 检查目录权限
$writableDirs = ['logs', 'uploads'];
foreach ($writableDirs as $dir) {
    $dirPath = __DIR__ . '/' . $dir;
    $exists = file_exists($dirPath);
    $writable = is_writable($dirPath);
    
    $healthCheck['checks']['directory_' . $dir] = [
        'status' => ($exists && $writable) ? 'healthy' : 'unhealthy',
        'exists' => $exists,
        'writable' => $writable
    ];
}

// 检查API路由
$healthCheck['checks']['api_routes'] = [
    'status' => 'healthy',
    'available_routes' => [
        '/api/user/login',
        '/api/user/register', 
        '/api/food/list',
        '/api/recipe/recommend',
        '/api/health/record'
    ]
];

// 如果有任何检查失败，整体状态设为unhealthy
foreach ($healthCheck['checks'] as $check) {
    if ($check['status'] === 'unhealthy') {
        $healthCheck['status'] = 'unhealthy';
        break;
    }
}

// 输出健康检查结果
http_response_code($healthCheck['status'] === 'healthy' ? 200 : 503);
echo json_encode($healthCheck, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

?>